//定义小仓库
import { defineStore } from 'pinia'
//@ts-ignore
import { cloneDeep } from 'lodash'
import { reqLogin, reqUserInfo, reqLoginOut } from '@/api/user/login'
import { contan, asycRouters, notfount } from '@/router/router.ts'
import router from '@/router'
function filterRouter(myRoutes: any, asycRouters: any) {
  return asycRouters.filter((item: any) => {
    if (myRoutes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRouter(myRoutes, item.children)
      }
      return true
    } else {
      return false
    }
  })
}

const useUserStore = defineStore('userStore', {
  state: () => {
    return {
      token: localStorage.getItem('token'),
      menuList: [],
      username: '',
      avatar: '',
    }
  },
  actions: {
    async login(data: any) {
      const res = await reqLogin(data)

      if (res.code == 200) {
        //存入token
        localStorage.setItem('token', res.data)
        this.token = res.data
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async getUserInfo() {
      let result = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        //路由处理
        let myRoutes = filterRouter(result.data.routes, cloneDeep(asycRouters))
        this.menuList = [...contan, ...myRoutes, ...notfount] as never[]
        ;[...myRoutes, ...notfount].forEach((element: any) => {
          router.addRoute(element)
        })

        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    async exitLogin() {
      let result = await reqLoginOut()
      if (result.code == 200) {
        localStorage.removeItem('token')
        this.username = ''
        this.avatar = ''
        this.token = ''
        return 'ok'
      } else {
        return Promise.reject('退出失败')
      }
    },
  },
  getters: {},
})

export default useUserStore
